<template>
  <div class="process-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>工序管理</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.processnameorcode" placeholder="请输入工序编号/名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="openCreateDialog">新增</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="batchDelete">删除</el-button>
      </div>

      <el-table
        :data="pagedRows"
        border
        stripe
        :loading="loading"
        class="process-table"
        height="640"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="processcode" label="工序编号" min-width="140" />
        <el-table-column prop="processname" label="工序名称" min-width="160" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="process_Description" label="工序说明" min-width="200" show-overflow-tooltip />
        <el-table-column prop="bz" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'create' ? '新建工序' : '编辑工序'" width="820px" :close-on-click-modal="false" @closed="onDialogClosed">
      <el-card shadow="never">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="detail-form">
          <div class="two-col">
            <el-form-item label="工序编号" prop="processcode">
              <div class="code-field">
                <el-input v-model="form.processcode" placeholder="请输入" :disabled="form.autoCode" />
                <el-switch v-model="form.autoCode" inline-prompt active-text="系统编号" inactive-text="系统编号" @change="onAutoCodeToggle" />
              </div>
            </el-form-item>
            <el-form-item label="工序名称" prop="processname">
              <el-input v-model="form.processname" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio-button :label="1">启用</el-radio-button>
                <el-radio-button :label="2">禁用</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="工序说明" prop="process_Description">
              <el-input v-model="form.process_Description" placeholder="请输入" />
            </el-form-item>
          </div>
          <el-form-item label="备注" prop="bz">
            <el-input v-model="form.bz" type="textarea" :rows="4" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </el-card>
      <template #footer>
        <el-button @click="dialog.visible = false">关闭</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// 这叫什么？叫“工序管理”
import { computed, onMounted, reactive, ref } from 'vue'
import https from '@/Http/http'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ArrowRight, HomeFilled, Setting, Menu } from '@element-plus/icons-vue'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

// 这是工序项数据结构
interface ProcessItem {
  id: number
  processcode: string
  processname: string
  status: number
  statusText: string
  process_Description: string
  bz: string
}

// 状态数据
const loading = ref(false)
const rows = ref<ProcessItem[]>([])
const multipleSelection = ref<ProcessItem[]>([])

// 分页数据
const pager = reactive({ page: 1, size: 10, total: 0 })
const pagedRows = computed(() => rows.value)

// 查询条件
const searchForm = reactive({
  processnameorcode: '',
  status: undefined as number | undefined,
})

// 弹窗与表单
const formRef = ref<FormInstance>()
const dialog = reactive({ visible: false, mode: 'create' as 'create' | 'edit' })
const form = reactive({
  id: undefined as number | undefined,
  processcode: '',
  processname: '',
  status: 1,
  process_Description: '',
  bz: '',
  autoCode: true,
})

// 表单校验规则
const rules = reactive<FormRules>({
  processcode: [{ required: true, message: '请输入工序编号', trigger: 'blur' }],
  processname: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

// 生成编号
const generateCode = () => {
  const now = new Date()
  const p = (n: number) => `${n}`.padStart(2, '0')
  return `GXBH${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`
}
// 自动编号切换
const onAutoCodeToggle = () => { if (form.autoCode) form.processcode = generateCode() }

// 查询工序列表
const fetchList = async () => {
  loading.value = true
  try {
    const response = await https.Reads.get(`/AManufacturing_process/GetProcessManagementList`, {
      params: {
        processnameorcode: searchForm.processnameorcode || '',
        status: searchForm.status ?? 0,
        PageIndex: pager.page,
        PageSize: pager.size,
      },
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取工序列表失败'))
    }
    const list = (payload?.data ?? payload?.Data ?? []) as ProcessItem[]
    rows.value = list
    pager.total = payload?.totalCount ?? payload?.TotalCount ?? list.length
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取工序列表失败'))
  } finally {
    loading.value = false
  }
}

// 查询/重置
const handleSearch = () => { fetchList() }
const handleReset = () => {
  searchForm.processnameorcode = ''
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

// 表格多选
const onSelectionChange = (arr: ProcessItem[]) => { multipleSelection.value = arr }

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.processcode = ''
  form.processname = ''
  form.status = 1
  form.process_Description = ''
  form.bz = ''
  form.autoCode = true
  formRef.value?.clearValidate()
  onAutoCodeToggle()
}

// 新建、编辑
const openCreateDialog = () => { dialog.mode = 'create'; resetForm(); dialog.visible = true }
const openEditDialog = (row: ProcessItem) => {
  dialog.mode = 'edit'
  form.id = row.id
  form.processcode = row.processcode
  form.processname = row.processname
  form.status = row.status
  form.process_Description = row.process_Description
  form.bz = row.bz
  form.autoCode = false
  dialog.visible = true
}

// 提交保存
const submitLoading = ref(false)
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    const payload = {
      id: form.id,
      processcode: form.processcode?.trim(),
      processname: form.processname?.trim(),
      status: form.status,
      process_Description: form.process_Description?.trim(),
      bz: form.bz?.trim()
    }
    try {
      const url = dialog.mode === 'create' ? '/AProcess_route/ProcessAdd' : '/AProcess_route/ProcessEdit'
      const response = await https.Writes.post(url, payload)
      const data = extractPayload(response)
      const success = isRequestSuccess(data)
      const message = getResponseMessage(
        data,
        success ? (dialog.mode === 'create' ? '新增工序成功' : '编辑工序成功') : '保存工序失败'
      )
      if (success) {
        ElMessage.success(message)
        dialog.visible = false
        fetchList()
      } else {
        ElMessage.error(message)
      }
    } catch (error) {
      ElMessage.error(getErrorMessage(error, '保存工序失败'))
    } finally {
      submitLoading.value = false
    }
  })
}

// 批量删除
const batchDelete = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择要删除的工序')
    return
  }
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条记录吗？`, '提示', { type: 'warning' })
    const results = await Promise.all(
      multipleSelection.value.map(item =>
        https.Writes.post('/AProcess_route/ProcessDelete', { id: item.id })
          .then(res => extractPayload(res))
          .catch(err => ({ __error: err }))
      )
    )
    let successCount = 0
    const failMessages: string[] = []
    results.forEach(result => {
      if ('__error' in result) {
        failMessages.push(getErrorMessage(result.__error, '删除失败'))
        return
      }
      if (isRequestSuccess(result)) {
        successCount += 1
      } else {
        failMessages.push(getResponseMessage(result, '删除失败'))
      }
    })
    if (successCount > 0) {
      ElMessage.success(`成功删除 ${successCount} 条工序`)
      multipleSelection.value = []
      fetchList()
    }
    if (failMessages.length) {
      ElMessage.error(failMessages.join('；'))
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(getErrorMessage(error, '批量删除失败'))
    }
  }
}

// 单行删除
const handleDelete = async (row: ProcessItem) => {
  try {
    await ElMessageBox.confirm(`确认删除「${row.processname}」吗？`, '提示', { type: 'warning' })
    const response = await https.Writes.post('/AProcess_route/ProcessDelete', { id: row.id })
    const data = extractPayload(response)
    const success = isRequestSuccess(data)
    const message = getResponseMessage(data, success ? '删除成功' : '删除失败')
    if (success) {
      ElMessage.success(message)
      fetchList()
    } else {
      ElMessage.error(message)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(getErrorMessage(error, '删除失败'))
    }
  }
}

// 弹窗关闭重置
const onDialogClosed = () => { resetForm() }

// 分页事件
const onPageSizeChange = (size: number) => { pager.size = size; pager.page = 1; fetchList() }
const onPageChange = (page: number) => { pager.page = page; fetchList() }

// 页面加载时初始化
onMounted(() => { fetchList() })
</script>

<style scoped>
.process-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.process-page::before { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 0; }
.process-page > * { position: relative; z-index: 1; }

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  position: relative;
  overflow: hidden;
}
.breadcrumb-nav :deep(.el-breadcrumb__inner) { color: rgba(255,255,255,0.9); font-weight: 500; display: inline-flex; align-items: center; gap: 6px; }
.breadcrumb-item.active :deep(.el-breadcrumb__inner) { color: #fff; font-weight: 600; }
.breadcrumb-icon { font-size: 16px; margin-right: 4px; }

.filter-card, .table-card { margin-bottom: 16px; background: rgba(255,255,255,0.95); backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0,0,0,0.08); }
.filter-form { display: flex; align-items: center; gap: 12px; }
.filter-actions { display: flex; gap: 12px; }
.toolbar { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.process-table { width: 100%; }

.detail-form { margin-top: 4px; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 16px 24px; }
.code-field { display: flex; align-items: center; gap: 12px; }

.mt-12 { margin-top: 12px; }
.w-180 { width: 180px; }
.flex-end { display: flex; justify-content: flex-end; }
</style>
